// utils/formatSize.ts
import { saveAs } from "file-saver";
export function formatBytes(
  bytes: number | string | undefined | null,
  decimals = 2,
  options?: { useBinary?: boolean; fixed?: boolean }
): string {
  if (bytes === null || bytes === undefined || bytes === '') return '-'

  // 尝试把字符串数字转成 number
  const value = typeof bytes === 'string' ? Number(bytes) : bytes
  if (Number.isNaN(value) || !isFinite(value)) return '-'

  const useBinary = options?.useBinary ?? true // true -> 1024，false -> 1000
  const thresh = useBinary ? 1024 : 1000
  if (Math.abs(value) < thresh) {
    return `${value} B`
  }

  const units = useBinary
    ? ['KB', 'MB', 'GB', 'TB', 'PB', 'EB']
    : ['KB', 'MB', 'GB', 'TB', 'PB', 'EB']

  let u = -1
  let bytesLeft = Math.abs(value)
  do {
    bytesLeft /= thresh
    u++
  } while (Math.abs(bytesLeft) >= thresh && u < units.length - 1)

  // 小数位数控制
  const factor = Math.pow(10, decimals)
  const rounded = Math.round(bytesLeft * factor) / factor
  const numStr = options?.fixed ? rounded.toFixed(decimals) : String(rounded)

  // 保留原有符号（如果是负数）
  const sign = value < 0 ? '-' : ''

  return `${sign}${numStr} ${units[u]}`
}
/**
 * 文件下载
 */
export function downloadFile(url: string, fileName?: string) {
if(!url){
  return 
}
saveAs(url, fileName)
}
/**
 * 将颜色值转换为标准 #RRGGBB 格式
 * @param input
 */
export function toHexColor(input: string) {
  // 去掉 0x 前缀
  const colorValue = input.startsWith('0x') ? input.slice(2) : input

  // 将剩余部分解析为十六进制数，再转成 6 位十六进制字符串
  const hexColor = parseInt(colorValue, 16).toString(16).padStart(6, '0')

  // 返回标准 #RRGGBB 格式
  return `#${hexColor}`
}
